package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    @PostMapping
    public R addCategory(@RequestBody Category category){
        categoryService.save(category);
        return R.success(category);
    }
    @GetMapping("/page")
    public R<Page> pageSelect(int page,int pageSize,String name){
        //分页构造器
        Page categoryPage = new Page(page,pageSize);
        //条件构造器
        //新建查询映射
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        //模糊查询，条件设置成判断语句是否为空，模糊查询条件，前段传递的条件
        queryWrapper.like(StringUtils.isEmpty(name),Category::getName,name);
        //根据修改时间的排序,查询条件
        queryWrapper.orderByDesc(Category::getUpdateTime);
        categoryService.page(categoryPage);
        return R.success(categoryPage);
    }
    @DeleteMapping
    public R deleteCategory(Long id){

        categoryService.check(id);
        return R.success("分类信息删除成功");
    }
    @PutMapping
    public R updateCategory(@RequestBody Category category){
        categoryService.updateById(category);
        return R.success("分类信息修改成功");
    }

    @GetMapping("/list")
    public R<List<Category>> list(Category category){
        //查询菜品分类，先新建查询
        LambdaQueryWrapper<Category> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //查询茶品分类，菜品属性为1，判断是否为空
        lambdaQueryWrapper.eq(category.getType()!=null,Category::getType,category.getType());
        //查询完之后按条件显示顺序，先通过表中定义属性排序，如果一致，按修改时间进行排序
        lambdaQueryWrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        //将条件付给MP自带的方法，得到集合
        List<Category> list = categoryService.list(lambdaQueryWrapper);
        //返回集合
        return R.success(list);

    }

}
